package repository

import (
	"buding-ai/internal/core"
	"buding-ai/internal/repository/model"
	"buding-ai/internal/web/response"
	"buding-ai/pkg/utils/paginate"
	"gorm.io/gorm"
	"sync"
)

var (
	agentRoleRepos *AgentRoleRepository
	agentRoleOnce  sync.Once
)

type AgentRoleRepository struct {
	db *gorm.DB
}

func GetAgentRoleRepository() *AgentRoleRepository {
	agentRoleOnce.Do(func() {
		agentRoleRepos = &AgentRoleRepository{
			db: core.DB,
		}
	})
	return agentRoleRepos
}
func (r *AgentRoleRepository) CheckAgentRoleExistsByName(name string) (bool, error) {
	var count int64
	if err := r.db.Model(&model.AgentRole{}).Where("name = ?", name).Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}

func (r *AgentRoleRepository) Create(entity model.AgentRole) error {
	return r.db.Create(&entity).Error
}

func (r *AgentRoleRepository) CloseByType(roleType int) error {
	return r.db.Model(&model.AgentRole{}).Where("type = ?", roleType).Update("status", 0).Error
}

func (r *AgentRoleRepository) GetById(id uint) (*model.AgentRole, error) {
	var agentRole model.AgentRole
	if err := r.db.First(&agentRole, id).Error; err != nil {
		return nil, err
	}
	return &agentRole, nil
}

func (r *AgentRoleRepository) DeleteById(id uint) error {
	return r.db.Delete(&model.AgentRole{}, id).Error
}

func (r *AgentRoleRepository) Update(entity *model.AgentRole) error {
	return r.db.Save(&entity).Error
}

func (r *AgentRoleRepository) GetPage(pageRequest paginate.PageRequest) (*paginate.PageResponse, error) {
	query := core.DB.Model(&model.AgentRole{})

	// 如果有搜索关键词，添加模糊查询条件
	if pageRequest.Keyword != "" {
		searchTerm := "%" + pageRequest.Keyword + "%"
		query = query.Where("name LIKE ? ", searchTerm)
	}

	// 执行分页查询
	var users []response.AgentRoleInfoVO
	pageResult, err := paginate.Paginator(query, pageRequest.Page, pageRequest.PageSize, pageRequest.Sort, pageRequest.Order, &users)

	if err != nil {
		return nil, err
	}

	return &pageResult, nil
}

func (r *AgentRoleRepository) List() ([]model.AgentRole, error) {
	var agentRoles []model.AgentRole
	if err := r.db.Find(&agentRoles).Error; err != nil {
		return nil, err
	}
	return agentRoles, nil
}
